<?php
$title = 'yyd';
require_once('head.php');
?>
<body>
<link rel="stylesheet" href="/newjingyu/static/element.css" />
<style>
    /* 公告弹窗样式 */
    .announcement-dialog {
        margin-top: 5vh !important;
    }
    .announcement-content {
        max-height: 60vh;
        overflow-y: auto;
        padding: 15px;
        line-height: 1.6;
        font-size: 16px;
    }
    .announcement-title {
        font-size: 20px;
        font-weight: bold;
        margin-bottom: 15px;
        color: #409EFF;
        text-align: center;
    }

    /* 移动端全屏适配 */
    @media (max-width: 768px) {
        .announcement-dialog {
            width: 100% !important;
            max-width: 100% !important;
            height: 100vh !important;
            max-height: 100vh !important;
            margin: 0 !important;
            top: 0 !important;
            left: 0 !important;
            border-radius: 0 !important; /* 去掉圆角 */
        }
        .el-dialog__header,
        .el-dialog__body,
        .el-dialog__footer {
            padding: 15px !important;
        }
        .el-dialog__header {
            position: sticky;
            top: 0;
            background: white; /* 防止滚动时标题栏遮挡 */
            z-index: 10;
        }
        .announcement-content {
            max-height: calc(100vh - 120px) !important; /* 减去标题和按钮高度 */
            overflow-y: auto;
            padding: 0 !important; /* 内容区不额外加padding */
        }
        .announcement-title {
            font-size: 18px !important;
            margin-bottom: 10px !important;
            text-align: left !important; /* 移动端标题左对齐 */
        }
        .dialog-footer {
            display: flex;
            justify-content: flex-end !important;
            padding: 10px 15px !important;
        }
        .el-button {
            padding: 8px 15px !important;
            font-size: 14px !important;
        }
        .el-checkbox {
            margin-right: 10px !important;
        }
    }
</style>

<div class="app-content-body">
  <div id="jingyu">
    <!-- 公告弹窗 -->
    <el-dialog 
        title="下单前注意事项" 
        :visible.sync="announcementVisible" 
        top="5vh"
        class="announcement-dialog"
        :before-close="handleAnnouncementClose">
        <div class="announcement-content">
            <div v-html="announcement.content"></div>
            <div style="margin-top: 20px; color: #999; font-size: 14px;">
                发布时间: {{announcement.publish_time}}
            </div>
        </div>
        <span slot="footer" class="dialog-footer">
            <el-checkbox v-model="notShowAgain">不再显示此公告</el-checkbox>
            <el-button type="primary" @click="closeAnnouncement">确 定</el-button>
        </span>
    </el-dialog>
     <!-- 添加弹窗 - 开始 -->
      <el-dialog title="添加宥马" :visible.sync="addymDialogVisible" width="650px" :before-close="addHandleClose">
        <el-form label-width="80px">
          <el-form-item label="用户账号">
            <el-input v-model="addymForm.phone" size="small" style="width: 200px;" placeholder="请输入账号"></el-input>
          </el-form-item>
          <el-form-item label="用户密码">
            <el-input v-model="addymForm.password" size="small" style="width: 200px;" placeholder="请输入密码"></el-input>
          </el-form-item>
          <el-form-item label="查询信息">
            <el-button type="primary" size="small" @click="getYmInfo" :loading="btnLoading.getymInfo">点击查询</el-button>
            <label style="color:red">单价:{{ymprice}}/公里</label>
          </el-form-item>
          <!-- 是否补跑开关 -->
            <el-form-item label="是否补跑">
              <el-switch
                v-model="addymForm.repair"
                active-text="补跑 1.5 倍扣费"
                inactive-text=""
                @change="handleMakeupChange"
              ></el-switch>
            </el-form-item>
            <el-form-item label="跑步类型">
              <el-radio-group 
                v-model="addymForm.run_type" 
                size="small"
                @change="handleRunTypeChange"
              >
                <el-radio-button 
                  v-for="option in runTypeOptions"
                  :key="option.value"
                  :label="option.value"
                  :disabled="option.disabled"
                >
                  {{ option.label }}
                </el-radio-button>
              </el-radio-group>
            </el-form-item>
          <el-form-item label="跑步区域">
            <el-select v-model="addymForm.zone_id" size="small" filterable remote :remote-method="remoteMethod" placeholder="请选择跑步区域" :disabled="!addymForm.student_id"
              style="width: 250px;">
              <el-option v-for="item in zoneOptions" :key="item.zone_id" :label="item.name"
                :value="item.zone_id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="公里数">
            <el-input-number v-model="addymForm.dis" :disabled="!addymForm.student_id" size="small" :min="1" :max="100"
              :precision="1" :step="0.1" label="公里数"></el-input-number>
          </el-form-item>
          <div v-show="genRunDateFlag">
            <el-divider>分配跑步时间</el-divider>
            <el-form-item label="开始日期">
              <el-date-picker v-model="runStartDate" @change="generateRunTimes('ym')" size="small" type="date"
                value-format="yyyy-MM-dd" placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="跑步时段">
              <el-time-picker is-range @change="generateRunTimes('ym')" style="width: 200px" size="small"
                v-model="runTimeRange" format="HH:mm" value-format="HH:mm" range-separator="—"
                start-placeholder="开始时间" end-placeholder="结束时间" placeholder="选择时间范围">
              </el-time-picker>
            </el-form-item>
            <el-form-item label="跑步周期">
              <el-select v-model="runWeek" @change="generateRunTimes('kp')" size="small" multiple
                placeholder="请选择跑步周期">
                <el-option v-for="item in weekOptions" :key="item.value" :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="跑步天数">
              <el-input-number v-model="runDay" @change="generateRunTimes('ym')" size="small" :min="0"
                :max="365" :step="1" label="跑步天数"></el-input-number>
              <el-button type="success" size="small"
                @click="()=>{genRunDateFlag = false;addFlag = true}">分配完成</el-button>
            </el-form-item>
            <el-form-item label="跑步时间">
              <template v-for="(item, index) in addymForm.task_list" :key="index">
                <el-date-picker v-model="item.start_time" :style="{'margin': '0 3px 3px 0'}"
                  value-format="yyyy-MM-dd HH:mm:ss" size="small" type="datetime" placeholder="选择日期时间">
                </el-date-picker>
              </template>
            </el-form-item>
            <el-divider></el-divider>
          </div>
          <el-form-item label="跑步时间" v-show="!genRunDateFlag">
            <div v-show="addymForm.task_list.length == 0">
              暂未分配
              <el-button class="ms-3" :disabled="!addymForm.student_id" type="primary" size="small"
                @click="genRunDateFlag = true">开始分配</el-button>
            </div>
            <template v-for="(item, index) in addymForm.task_list" :key="index">
              <el-date-picker v-model="item.start_time" disabled="!genRunDateFlag"
                :style="{'margin': '0 3px 3px 0'}" value-format="yyyy-MM-dd HH:mm:ss" size="small"
                type="datetime" placeholder="选择日期时间">
              </el-date-picker>
            </template>
          </el-form-item>
          <div v-show="addFlag">
            <el-form-item label="价格总计">
              <el-input class="col-md-3" v-model="total" size="small" disabled=""></el-input>
            </el-form-item>
            <el-form-item>
              <div class="d-flex">
                <el-button type="primary" size="small" @click="handleymAdd" :loading="btnLoading.handleymAdd">确认下单</el-button>
                <el-button type="warning" size="small"
                  @click="()=>{genRunDateFlag = true;addFlag = false}">重新分配</el-button>
              </div>
            </el-form-item>
          </div>
        </el-form>
      </el-dialog>
      <!-- 添加弹窗 - 结束 -->      
    
    <!-- 添加弹窗 - 开始 -->
      <el-dialog title="添加订单" :visible.sync="addkpDialogVisible" width="650px" :before-close="addHandleClose">
        <el-form label-width="80px">
          <el-form-item label="用户账号">
            <el-input v-model="addkpForm.phone" size="small" style="width: 200px;" placeholder="请输入账号"></el-input>
          </el-form-item>
          <el-form-item label="用户密码">
            <el-input v-model="addkpForm.password" size="small" style="width: 200px;" placeholder="请输入密码"></el-input>
          </el-form-item>
          <el-form-item label="查询信息">
            <el-button type="primary" size="small" @click="getkpInfo" :loading="btnLoading.getkpInfo">点击查询</el-button>
            <label style="color:red">单价:{{kpprice}}/公里</label>
          </el-form-item>
          <el-form-item label="跑步类型">
            <el-radio v-model="addkpForm.run_type" label="1" border size="small"
              :disabled="!addkpForm.student_id">自由跑</el-radio>
          </el-form-item>
          <el-form-item label="跑步区域">
            <el-select v-model="addkpForm.zone_id" size="small" filterable remote :remote-method="remoteMethod" placeholder="请选择跑步区域" :disabled="!addkpForm.student_id"
              style="width: 250px;">
              <el-option v-for="item in zoneOptions" :key="item.zone_id" :label="item.name"
                :value="item.zone_id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="公里数">
            <el-input-number v-model="addkpForm.dis" :disabled="!addkpForm.student_id" size="small" :min="1" :max="100"
              :precision="1" :step="0.1" label="公里数"></el-input-number>
          </el-form-item>
          <el-form-item label="最快配速">
            <el-input-number v-model="addkpForm.min_minute" :disabled="!addkpForm.student_id" size="small" :min="3"
              :max="6" :step="1" label="最快配速"></el-input-number>
            <span style="margin-left: 10px;font-size: 14px;">分钟/公里</span>
          </el-form-item>
          <el-form-item label="最慢配速">
            <el-input-number v-model="addkpForm.max_minute" :disabled="!addkpForm.student_id" size="small" :min="8"
              :max="15" :step="1" label="最慢配速"></el-input-number>
            <span style="margin-left: 10px;font-size: 14px;">分钟/公里</span>
          </el-form-item>
          <div v-show="genRunDateFlag">
            <el-divider>分配跑步时间</el-divider>
            <el-form-item label="开始日期">
              <el-date-picker v-model="runStartDate" @change="generateRunTimes('kp')" size="small" type="date"
                value-format="yyyy-MM-dd" placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="跑步时段">
              <el-time-picker is-range @change="generateRunTimes('kp')" style="width: 200px" size="small"
                v-model="runTimeRange" format="HH:mm" value-format="HH:mm" range-separator="—"
                start-placeholder="开始时间" end-placeholder="结束时间" placeholder="选择时间范围">
              </el-time-picker>
            </el-form-item>
            <el-form-item label="跑步周期">
              <el-select v-model="runWeek" @change="generateRunTimes('kp')" size="small" multiple
                placeholder="请选择跑步周期">
                <el-option v-for="item in weekOptions" :key="item.value" :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="跑步天数">
              <el-input-number v-model="runDay" @change="generateRunTimes('kp')" size="small" :min="0"
                :max="365" :step="1" label="跑步天数"></el-input-number>
              <el-button type="success" size="small"
                @click="()=>{genRunDateFlag = false;addFlag = true}">分配完成</el-button>
            </el-form-item>
            <el-form-item label="跑步时间">
              <template v-for="(item, index) in addkpForm.task_list" :key="index">
                <el-date-picker v-model="item.start_time" :style="{'margin': '0 3px 3px 0'}"
                  value-format="yyyy-MM-dd HH:mm:ss" size="small" type="datetime" placeholder="选择日期时间">
                </el-date-picker>
              </template>
            </el-form-item>
            <el-divider></el-divider>
          </div>
          <el-form-item label="跑步时间" v-show="!genRunDateFlag">
            <div v-show="addkpForm.task_list.length == 0">
              暂未分配
              <el-button class="ms-3" :disabled="!addkpForm.student_id" type="primary" size="small"
                @click="genRunDateFlag = true">开始分配</el-button>
            </div>
            <template v-for="(item, index) in addkpForm.task_list" :key="index">
              <el-date-picker v-model="item.start_time" disabled="!genRunDateFlag"
                :style="{'margin': '0 3px 3px 0'}" value-format="yyyy-MM-dd HH:mm:ss" size="small"
                type="datetime" placeholder="选择日期时间">
              </el-date-picker>
            </template>
          </el-form-item>
          <div v-show="addFlag">
            <el-form-item label="价格总计">
              <el-input class="col-md-3" v-model="total" size="small" disabled=""></el-input>
            </el-form-item>
            <el-form-item>
              <div class="d-flex">
                <el-button type="primary" size="small" @click="handlekpAdd" :loading="btnLoading.handlekpAdd">确认下单</el-button>
                <el-button type="warning" size="small"
                  @click="()=>{genRunDateFlag = true;addFlag = false}">重新分配</el-button>
              </div>
            </el-form-item>
          </div>
        </el-form>
      </el-dialog>
      <!-- 添加弹窗 - 结束 -->      
      
      
    <!-- 添加弹窗 - 开始 -->
    <el-dialog title="添加订单" :visible.sync="addDialogVisible" width="650px" :before-close="addHandleClose">
      <el-form label-width="80px">
        <el-form-item label="用户学校">
          <el-select v-model="addForm.school_id" size="small" filterable remote :remote-method="remoteMethod" :loading="schoolLoading" placeholder="请输入学校名"
            style="width: 250px;">
            <el-option v-for="item in schoolOptions" :key="item.school_id" :label="item.name"
              :value="item.school_id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户账号">
          <el-input v-model="addForm.number" size="small" style="width: 200px;" placeholder="请输入账号"></el-input>
        </el-form-item>
        <el-form-item label="用户密码">
          <el-input v-model="addForm.password" size="small" style="width: 200px;" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="查询信息">
          <el-button type="primary" size="small" :loading="btnLoading.getUserInfo" @click="getUserInfo">点击查询</el-button>
          <label style="color:red">单价:{{price}}/公里</label>
        </el-form-item>
        <el-form-item label="跑步区域">
          <el-select v-model="addForm.zone_id" size="small" placeholder="请选择跑步区域" :disabled="!addForm.student_id"
            style="width: 250px;">
            <el-option v-for="item in zoneOptions" :key="item.zone_id" :label="item.name"
              :value="item.zone_id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="公里数">
          <el-input-number v-model="addForm.dis" :disabled="!addForm.student_id" size="small" :min="1" :max="100"
            :precision="1" :step="0.1" label="公里数"></el-input-number>
        </el-form-item>
        <div v-show="genRunDateFlag">
          <el-divider>分配跑步时间</el-divider>
          <el-form-item label="开始日期">
            <el-date-picker v-model="runStartDate" @change="generateRunTimes('yyd')" size="small" type="date"
              value-format="yyyy-MM-dd" placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="跑步时段">
            <el-time-picker is-range @change="generateRunTimes('yyd')" style="width: 200px" size="small"
              v-model="runTimeRange" format="HH:mm" value-format="HH:mm" range-separator="—"
              start-placeholder="开始时间" end-placeholder="结束时间" placeholder="选择时间范围">
            </el-time-picker>
          </el-form-item>
          <el-form-item label="跑步周期">
            <el-select v-model="runWeek" @change="generateRunTimes('yyd')" size="small" multiple
              placeholder="请选择跑步周期">
              <el-option v-for="item in weekOptions" :key="item.value" :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="跑步天数">
            <el-input-number v-model="runDay" @input="generateRunTimes('yyd')" size="small" :min="0"
              :max="365" :step="1" label="跑步天数"></el-input-number>
            <el-button type="success" size="small"
              @click="()=>{genRunDateFlag = false;addFlag = true}">分配完成</el-button>
          </el-form-item>
          <el-form-item label="跑步时间">
            <template v-for="(item, index) in addForm.task_list" :key="index">
              <el-date-picker v-model="item.start_time" :style="{'margin': '0 3px 3px 0'}"
                value-format="yyyy-MM-dd HH:mm:ss" size="small" type="datetime" placeholder="选择日期时间">
              </el-date-picker>
            </template>
          </el-form-item>
          <el-divider></el-divider>
        </div>
        <el-form-item label="跑步时间" v-show="!genRunDateFlag">
          <div v-show="addForm.task_list.length == 0">
            暂未分配
            <el-button class="ms-3" :disabled="!addForm.student_id" type="primary" size="small"
              @click="genRunDateFlag = true">开始分配</el-button>
          </div>
          <template v-for="(item, index) in addForm.task_list" :key="index">
            <el-date-picker v-model="item.start_time" disabled="!genRunDateFlag"
              :style="{'margin': '0 3px 3px 0'}" value-format="yyyy-MM-dd HH:mm:ss" size="small"
              type="datetime" placeholder="选择日期时间">
            </el-date-picker>
          </template>
        </el-form-item>
        <div v-show="addFlag">
          <el-form-item label="价格总计">
            <el-input class="col-md-3" v-model="total" size="small" disabled=""></el-input>
          </el-form-item>
          <el-form-item>
            <div class="d-flex">
              <el-button type="primary" size="small" @click="handleAdd" :loading="btnLoading.handleAdd">确认下单</el-button>
              <el-button type="warning" size="small"
                @click="()=>{genRunDateFlag = true;addFlag = false}">重新分配</el-button>
            </div>
          </el-form-item>
        </div>
      </el-form>
    </el-dialog>
     
     
     <!-- 乐跑弹窗 -->
      <el-dialog title="添加订单" :visible.sync="addlpDialogVisible" width="650px" :before-close="addHandleClose">
        <el-form label-width="80px">
          <el-form-item label="用户账号">
            <el-input v-model="addlpForm.uid" size="small" style="width: 200px;" placeholder="请输入账号"></el-input>
          </el-form-item>
          <el-form-item label="查询信息">
            <el-button type="primary" size="small" @click="getlpInfo" :loading="btnLoading.getlpInfo">点击查询</el-button>
             <label style="color:red">单价:{{lpprice}}/次</label>
          </el-form-item>
          <el-form-item label="跑步类型">
            <el-radio-group v-model="addlpForm.run_type" size="small" :disabled="!addlpForm.uid">
              <el-radio-button label="VAL">有效跑</el-radio-button>
              <el-radio-button label="FREE">自由跑</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-alert
            v-show="addlpForm.run_type==='FREE'"
            title="自由跑不关联有效成绩，一般用于完成老师私下布置的任务，请确认学生需求"
            type="warning" class="my-2">
          </el-alert>
          <el-form-item label="跑步区域">
            <el-select v-model="addlpForm.zone_id" size="small" placeholder="请选择跑步区域" :disabled="!addlpForm.uid"
              style="width: 250px;">
              <el-option v-for="item in zonelpOptions" :key="item.zone_id" :label="item.name"
                :value="item.zone_id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="公里数">
            <el-input-number v-model="addlpForm.dis" :disabled="!addlpForm.uid" size="small" :min="1" :max="100"
              :precision="1" :step="0.1" label="公里数"></el-input-number>
          </el-form-item>
          <div v-show="genRunDateFlag">
            <el-divider>分配跑步时间</el-divider>
            <el-form-item label="开始日期">
              <el-date-picker v-model="runStartDate" @change="generateRunTimes('lp')" size="small" type="date"
                value-format="yyyy-MM-dd" placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="跑步时段">
              <el-time-picker is-range @change="generateRunTimes('lp')" style="width: 200px" size="small"
                v-model="runTimeRange" format="HH:mm" value-format="HH:mm" range-separator="—"
                start-placeholder="开始时间" end-placeholder="结束时间" placeholder="选择时间范围">
              </el-time-picker>
            </el-form-item>
            <el-form-item label="跑步周期">
              <el-select v-model="runWeek" @change="generateRunTimes('lp')" size="small" multiple
                placeholder="请选择跑步周期">
                <el-option v-for="item in weekOptions" :key="item.value" :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="跑步天数">
              <el-input-number v-model="runDay" @input="generateRunTimes('lp')" size="small" :min="0"
                :max="365" :step="1" label="跑步天数"></el-input-number>
              <el-button type="success" size="small"
                @click="()=>{genRunDateFlag = false;addFlag = true}">分配完成</el-button>
            </el-form-item>
            <el-form-item label="跑步时间">
              <template v-for="(item, index) in addlpForm.task_list" :key="index">
                <el-date-picker v-model="item.start_time" :style="{'margin': '0 3px 3px 0'}"
                  value-format="yyyy-MM-dd HH:mm:ss" size="small" type="datetime" placeholder="选择日期时间">
                </el-date-picker>
              </template>
            </el-form-item>
            <el-divider></el-divider>
          </div>
          <el-form-item label="跑步时间" v-show="!genRunDateFlag">
            <div v-show="addForm.task_list.length == 0">
              暂未分配
              <el-button class="ms-3" :disabled="!addlpForm.uid" type="primary" size="small"
                @click="genRunDateFlag = true">开始分配</el-button>
            </div>
            <template v-for="(item, index) in addlpForm.task_list" :key="index">
              <el-date-picker v-model="item.start_time" disabled="!genRunDateFlag"
                :style="{'margin': '0 3px 3px 0'}" value-format="yyyy-MM-dd HH:mm:ss" size="small"
                type="datetime" placeholder="选择日期时间">
              </el-date-picker>
            </template>
          </el-form-item>
          <div v-show="addFlag">
            <el-form-item label="价格总计">
              <el-input class="col-md-3" v-model="total" size="small" disabled=""></el-input>
            </el-form-item>
            <el-form-item>
              <div class="d-flex">
                <el-button type="primary" size="small" @click="handlelpAdd" :loading="btnLoading.handlelpAdd">确认下单</el-button>
                <el-button type="warning" size="small"
                  @click="()=>{genRunDateFlag = true;addFlag = false}">重新分配</el-button>
              </div>
            </el-form-item>
          </div>
        </el-form>
      </el-dialog>
      <!-- 添加弹窗 - 结束 -->
      <!-- 编辑弹窗 - 开始 -->
      <el-dialog title="编辑订单" :visible.sync="editDialogVisible" width="650px" :before-close="editHandleClose">
        <el-form label-width="80px">
          <el-form-item label="温馨提示">您当前跑步次数剩余：<font color="red">{{ runDay }}</font> 次</el-form-item>
          <el-form-item label="用户学校">
            <el-input v-model="editForm.school_name" size="small" style="width: 200px;" placeholder="请输入学校"
              disabled=""></el-input>
          </el-form-item>
          <el-form-item label="用户账号">
            <el-input v-model="editForm.number" size="small" style="width: 200px;" placeholder="请输入账号"
              disabled=""></el-input>
          </el-form-item>
          <el-form-item label="用户密码">
            <el-input v-model="editForm.password" size="small" style="width: 200px;" placeholder="请输入密码"
              disabled=""></el-input>
          </el-form-item>
          <el-form-item label="跑步区域">
            <el-input v-model="editForm.zone_name" size="small" style="width: 200px;" placeholder="请输入跑步区域"
              disabled=""></el-input>
          </el-form-item>
          <el-form-item label="公里数">
            <el-input-number v-model="editForm.dis" disabled="" size="small" :min="1" :max="100" :precision="1"
              :step="0.1" label="公里数"></el-input-number>
          </el-form-item>
          <div v-show="genRunDateFlag">
            <el-divider>分配跑步时间</el-divider>
            <el-form-item label="开始日期">
              <el-date-picker v-model="runStartDate" @change="generateRunTimes('edit')" size="small" type="date"
                value-format="yyyy-MM-dd" placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="跑步时段">
              <el-time-picker is-range @change="generateRunTimes('edit')" style="width: 200px" size="small"
                v-model="runTimeRange" format="HH:mm" value-format="HH:mm" range-separator="—"
                start-placeholder="开始时间" end-placeholder="结束时间" placeholder="选择时间范围">
              </el-time-picker>
            </el-form-item>
            <el-form-item label="跑步周期">
              <el-select v-model="runWeek" @change="generateRunTimes('edit')" size="small" multiple
                placeholder="请选择跑步周期">
                <el-option v-for="item in weekOptions" :key="item.value" :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="跑步天数">
              <el-input-number v-model="runDay" disabled="" size="small" :min="0" :max="365" :step="1"
                label="跑步天数"></el-input-number>
              <el-button type="success" size="small"
                @click="()=>{genRunDateFlag = false;addFlag = true}">分配完成</el-button>
            </el-form-item>
            <el-form-item label="跑步时间">
              <template v-for="(item, index) in editForm.task_list" :key="index">
                <el-date-picker v-model="item.start_time" :style="{'margin': '0 3px 3px 0'}"
                  value-format="yyyy-MM-dd HH:mm:ss" size="small" type="datetime" placeholder="选择日期时间">
                </el-date-picker>
              </template>
            </el-form-item>
            <el-divider></el-divider>
          </div>
          <el-form-item label="跑步时间" v-show="!genRunDateFlag">
            <div v-show="editForm.task_list.length == 0">
              暂未分配
              <el-button class="ms-3" type="primary" size="small"
                @click="genRunDateFlag = true">开始分配</el-button>
            </div>
            <template v-for="(item, index) in editForm.task_list" :key="index">
              <el-date-picker v-model="item.start_time" disabled="!genRunDateFlag"
                :style="{'margin': '0 3px 3px 0'}" value-format="yyyy-MM-dd HH:mm:ss" size="small"
                type="datetime" placeholder="选择日期时间">
              </el-date-picker>
            </template>
          </el-form-item>
          <div v-show="addFlag">
            <el-form-item>
              <div class="d-flex">
                <el-button type="primary" size="small" @click="handleEdit">确认修改</el-button>
                <el-button type="warning" size="small"
                  @click="()=>{genRunDateFlag = true;addFlag = false}">重新分配</el-button>
              </div>
            </el-form-item>
          </div>
        </el-form>
      </el-dialog>
      <!-- 编辑弹窗 - 结束 -->
      <!-- 任务弹窗 - 开始 -->
      <el-dialog title="任务详情" :visible.sync="taskDialogVisible" fullscreen :before-close="taskHandleClose">
        <el-table :data="taskData" v-loading="taskLoading" border size="small">
          <el-table-column align="center" property="run_task_id" label="任务ID" width="80"></el-table-column>
          <el-table-column align="center" property="start_time" label="起始时间" width="380">
            <template slot-scope="scope">
              <div v-if="!scope.row.edit">{{ scope.row.start_time }}</div>
              <div v-else style="display: flex;align-items: center;justify-content: center;">
                <el-date-picker v-model="scope.row.start_time" value-format="yyyy-MM-dd HH:mm:ss" size="small"
                  type="datetime" placeholder="选择日期时间">
                </el-date-picker>
                <i class="el-icon-check" @click="doneTaskEdit(scope.$index, scope.row)"
                  style="color: #409EFF;font-size: 20px;margin: 0 6px;cursor: pointer;"></i>
                <i class="el-icon-close" @click="closeTaskEdit(scope.$index, scope.row)"
                  style="font-size: 20px;margin: 0 6px;cursor: pointer;"></i>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" property="end_time" label="结束时间" width="200"></el-table-column>
          <el-table-column align="center" property="min_dis" label="公里数" width="80"></el-table-column>
          <el-table-column align="center" property="status_display" label="状态" width="100">
            <template slot-scope="scope">
              <el-tag type="primary" size="small" v-if="scope.row.status_display == '未开始'">未开始</el-tag>
              <el-tag type="success" size="small" v-else-if="scope.row.status_display == '成功'">已完成</el-tag>
              <el-tag type="info" size="small" v-else-if="scope.row.status_display == '退款'">已退款</el-tag>
              <el-tag type="warning" size="small" v-else>{{ scope.row.status_display }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" property="info" label="信息"></el-table-column>
          <el-table-column align="center" label="操作" width="300">
            <template slot-scope="scope">
              <el-button v-if="scope.row.status_display == '未开始'" type="success" size="small"
                @click="handleTaskEdit(scope.$index, scope.row)">修改时间</el-button>
              <el-button :loading="delayBtnLoading" v-if="scope.row.status_display == '未开始'" type="primary"
                size="small" @click="delayTask(scope.$index, scope.row)">移至最后</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>
      <!-- 任务弹窗 - 结束 -->
      <!-- 列表 - 开始 -->
      <el-card class="box-card">
        <div class="card-body">
          <div class="row">
            <div class="col-md-6 mb-2">
                <el-button type="primary" size="medium" plain @click="addymDialogVisible = true">添加宥马</el-button>
              <el-button type="primary" size="medium" plain @click="addkpDialogVisible = true">添加KEEP</el-button>
              <el-button type="primary" size="medium" plain @click="addDialogVisible = true">添加云运动</el-button>
              <el-button type="primary" size="medium" plain @click="addlpDialogVisible = true">添加乐跑</el-button>
            </div>
            <el-input class="col-md-6 mb-2" size="medium" placeholder="关键词" v-model="search.keywords"
              class="input-with-select">
              <el-select v-model="search.type" size="medium" style="width: 100px" placeholder="条件"
                slot="prepend">
                <el-option label="订单ID" value="1"></el-option>
                <el-option label="下单账号" value="2"></el-option>
                <el-option label="下单密码" value="3"></el-option>
                <?php if ($userrow['uid'] == 1) { ?>
                  <el-option label="用户UID" value="4"></el-option>
                <?php } ?>
              </el-select>
              <el-button slot="append" size="medium" icon="el-icon-search" @click="get">搜索</el-button>
            </el-input>
          </div>
          <el-table :data="tableData" style="width: 100%" v-loading="tableLoading">
            <el-table-column align="center" prop="id" label="ID" width="60"></el-table-column>
            <?php if ($userrow['uid'] == 1) { ?>
              <el-table-column align="center" prop="uid" label="UID" width="60"></el-table-column>
            <?php } ?>
            <el-table-column align="center" label="账号信息" width="120">
              <template slot-scope="scope">
                <div>{{ scope.row.user }}</div>
                <div>{{ scope.row.pass }}</div>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="school_name" label="学校"></el-table-column>
            <el-table-column align="center" label="类型" width="80">
              <template slot-scope="scope">
                <el-tag type="primary" v-if="scope.row.run_type==1">阳光跑</el-tag>
              </template>
            </el-table-column>
            <el-table-column align="center" label="软件" width="120">
              <template slot-scope="scope">
                <div style="display: flex; justify-content: center;">
                  <!-- 云运动 - 亮绿色 -->
                  <el-tag 
                    v-if="scope.row.type==1" 
                    style="background-color: #52c41a; color: white; border: none; font-weight: bold;"
                  >云运动</el-tag>
                  
                  <!-- 步道乐跑 - 亮橙色 -->
                  <el-tag 
                    v-else-if="scope.row.type==4" 
                    style="background-color: #fa8c16; color: white; border: none; font-weight: bold;"
                  >宥马运动</el-tag>
                  
                  <!-- KEEP - 亮红色 -->
                  <el-tag 
                    v-else-if="scope.row.type==3" 
                    style="background-color: #f5222d; color: white; border: none; font-weight: bold;"
                  >KEEP</el-tag>
                  
                  <!-- 宥马运动 - 亮蓝色 -->
                  <el-tag 
                    v-else-if="scope.row.type==2" 
                    style="background-color: #1890ff; color: white; border: none; font-weight: bold;"
                  >步道乐跑</el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="num" label="次数" width="50"></el-table-column>
            <el-table-column align="center" label="公里数" width="80">
              <template slot-scope="scope">{{ scope.row.distance }} KM</template>
            </el-table-column>
            <el-table-column align="center" prop="status_display" label="订单状态" width="90">
              <template slot-scope="scope">
                <el-tag type="primary" v-if="scope.row.status_display=='正常'">正常</el-tag>
                <el-tag type="success" v-else-if="scope.row.status_display=='全部完成'">全部完成</el-tag>
                <el-tag type="info" v-else-if="scope.row.status_display=='已退款'">已退款</el-tag>
                <el-tag type="warning" v-else>{{ scope.row.status_display }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="addtime" label="下单时间" width="150"></el-table-column>
            <el-table-column align="center" label="用户操作" width="120">
              <template slot-scope="scope">
                <el-dropdown>
                  <el-button type="primary" size="mini" style="margin-left: 8px;">
                    操作<i class="el-icon-arrow-down el-icon--right"></i>
                  </el-button>
                  <el-dropdown-menu slot="dropdown" style="z-index: 9999; background-color: #fff;">
<el-dropdown-item 
  @click.native="openTaskDialog(scope.row)" 
  type="primary" 
  size="mini" 
  style="width: 100%;">
  任务详情
</el-dropdown-item>
                    <el-dropdown-item v-if="scope.row.status_display!=='全部完成' && scope.row.status_display!=='已退款'"
                      @click.native="handleRefund(scope.row)" type="primary" size="mini" style="width: 100%; " :loading="btnLoading.handleRefund">申请退款</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="pagination.page" :page-sizes="[20, 50, 100, 300]" :page-size="pagination.limit"
            layout="total, sizes, prev, pager, next" :total="pagination.total">
          </el-pagination>
        </div>
      </el-card>
      <!-- 列表 - 结束 -->
    </div>
  </div>
</div>

<?php require_once("footer.php"); ?>
<script src="/newjingyu/static/axios.min.js"></script>
<script src="/newjingyu/static/vue.min.js"></script>
<script src="/newjingyu/static/vue-resource.min.js"></script>
<script src="/newjingyu/static/element.js"></script>
<script>
new Vue({
  el: '#jingyu',
  data() {
    return {
     // ...其他原有数据...
    btnLoading: {
      getUserInfo: false,
      getkpInfo: false,
      getymInfo: false,
      getlpInfo: false,
      handleAdd: false,
      handleymAdd: false,
      handlekpAdd: false,
      handlelpAdd: false,
      handleEdit: false,
      handleRefund: false,
      delayTask: false,
      doneTaskEdit: false,
      search: false
    },    
    runTypeOptions:[],
      type: '',
      yyd_order_id: '',
      addlpForm: {
        uid: '',
        run_type: 'VAL',
        zone_id: '',
        dis: 2.0,
        task_list: [],
        school_name:''
      },  
     addymForm: {
        school_id: '',
        repair: false,
        number: '',
        password: '',
        student_id: '',
        school_name: '',
        zone_id: '',
        dis: 2,
        task_list: [],
        run_rule_item_id: ''
      },
    addkpForm: {
        school_id: '',
        number: '',
        password: '',
        student_id: '',
        school_name: '',
        zone_id: '',
        dis: 2,
        task_list: [],
        run_rule_item_id: ''
      },
      addForm: {
        school_id: '',
        number: '',
        password: '',
        student_id: '',
        school_name: '',
        zone_id: '',
        dis: 2,
        task_list: [],
        run_rule_item_id: ''
      },
      schoolOptions: [],
      schoolLoading: false,
      zoneOptions: [],
      zonelpOptions: [],
      runRules: [],
      genRunDateFlag: false,
      addFlag: false,
      runDay: 0,
      total: 0,
      price: 0.14,
      lpprice: 0.18,
      kpprice: 0.35,
      ymprice: 0.5,
      addlpDialogVisible: false,
      addDialogVisible: false,
      addymDialogVisible: false,
      addkpDialogVisible: false,
      editDialogVisible: false,
      taskDialogVisible: false,
      taskLoading: false,
      delayBtnLoading: false,
      tableLoading: false,
      runStartDate: new Date().toISOString().split('T')[0], // 格式化为 YYYY-MM-DD
      runTimeRange: '',
      runWeek: [1, 2, 3, 4, 5, 6, 0],
      editForm: {
        id: '',
        uid: '',
        run_type: '1',
        zone_name: '',
        school_name: '',
        dis: 1,
        task_list: []
      },
      search: {
        type: '',
        keywords: ''
      },
      pagination: {
        page: 1,
        limit: 20,
        total: 0
      },
      // 新增公告相关数据
                announcementVisible: false,
                 notShowAgain: false,
                 announcement: {
                    title: "系统公告",
                    content: "鲸鱼乐跑授权地址https://www.yjer.buzz/zhiyinsq/#/bdlp新增设备授权，仅需授权安卓设备，苹果设备无需进行设备授权，扫码授权成功之后页面会提示学生进行设备授权，详细：https://www.yjer.buzz/zhiyinsq/#/bdlp/android，苹果：https://www.yjer.buzz/zhiyinsq/#/bdlp/ios<br/><br/>学生微信接收推送步骤： 1. 学生在微信中打开链接: wxpusher.zjiecode.com/wxuser/?type=1&id=22232#/follow 点击“关注” 2. 在公众号窗口发送信息: #22232+空格+您的乐跑ID (如: #22232 8765432) 。 3. 跑步情况（授权失效等）会收到推送。",
                    publish_time: "2025-05-01 10:00:00"
            },
      tableData: [],
      weekOptions: [
        { value: 1, label: '周一' },
        { value: 2, label: '周二' },
        { value: 3, label: '周三' },
        { value: 4, label: '周四' },
        { value: 5, label: '周五' },
        { value: 6, label: '周六' },
        { value: 0, label: '周日' }
      ],
      taskData: []
    };
  },
  watch: {
    runDay(newVal) {
      if (this.addDialogVisible) {
        this.generateRunTimes('yyd');
      } else if (this.addlpDialogVisible) {
        this.generateRunTimes('lp');
      } else if (this.editDialogVisible) {
        this.generateRunTimes('edit');
      } else if (this.addkpDialogVisible) {
        this.generateRunTimes('kp');
      }else if (this.addymDialogVisible) {
        this.generateRunTimes('ym');
      }
    }
  },
  methods: {
      handleMakeupChange(val) {
      this.$message({
        type: 'warning',
        message: val ? '已开启补跑（费用×1.5）' : '已关闭补跑'
      })
    },
      // 通用防重复点击包装器
  async preventDuplicateClick(btnName, fn) {
    if (this.btnLoading[btnName]) return;
    this.btnLoading[btnName] = true;
    try {
      await fn();
    } catch (error) {
      console.error(`${btnName} error:`, error);
      this.$message.error(error.response?.data?.msg || error.message || '操作失败');
    } finally {
      this.btnLoading[btnName] = false;
    }
  },
                       // 新增公告相关方法
                showAnnouncement() {
                    this.announcementVisible = true;
                },
                closeAnnouncement() {
                    if (this.notShowAgain) {
                        // 用户选择不再显示，保存到本地存储
                        localStorage.setItem('hideAnnouncement', 'true');
                    }
                    this.announcementVisible = false;
                },
                handleAnnouncementClose(done) {
                    if (this.notShowAgain) {
                        localStorage.setItem('hideAnnouncement', 'true');
                    }
                    done();
                },
                // getLatestAnnouncement() {
                //     // 从服务器获取最新公告
                //     this.$http.post("/leidian/api.php?act=getAnnouncement", {}, {
                //         emulateJSON: true
                //     }).then(function (data) {
                //         if (data.data.code == 1) {
                //             this.announcement = data.data.data;
                //         }
                //     });
                // },
    // 通用生成跑步时间方法
    generateRunTimes(formType) {
      let form;
      switch(formType) {
        case 'yyd':
          form = this.addForm;
          break;
        case 'ym':
          form = this.addymForm;
          break;
        case 'kp':
          form = this.addkpForm;
          break;  
        case 'lp':
          form = this.addlpForm;
          break;
        case 'edit':
          form = this.editForm;
          break;
        default:
          return;
      }
      
      form.task_list = [];
      
      // 参数检查
      if (!this.runStartDate || !this.runDay) {
        return;
      }
      
      if (!this.runTimeRange || this.runTimeRange.length !== 2) {
        return;
      }
      
      if (!this.runWeek || this.runWeek.length === 0) {
        return;
      }

      const [startTime, endTime] = this.runTimeRange;
      const startDate = new Date(this.runStartDate);
      const startMinutes = this.timeToMinutes(startTime);
      const endMinutes = this.timeToMinutes(endTime);
      
      let generatedDays = 0;
      let currentDate = new Date(startDate);
      
      // 按选择的周几生成日期
      while (generatedDays < this.runDay) {
        const dayOfWeek = currentDate.getDay();
        
        if (this.runWeek.includes(dayOfWeek)) {
          const randomMinutes = this.getRandomInt(startMinutes, endMinutes - 30);
          const randomTime = this.minutesToTime(randomMinutes);
          
          const startDateTime = `${currentDate.toISOString().split('T')[0]} ${randomTime}:00`;
          const endDateTime = `${currentDate.toISOString().split('T')[0]} ${this.minutesToTime(randomMinutes + 30)}:00`;
          
          form.task_list.push({
            start_time: startDateTime,
            end_time: endDateTime
          });
          
          generatedDays++;
        }
        
        currentDate.setDate(currentDate.getDate() + 1);
      }
      
      // 计算价格总计
      if (formType === 'lp') {
        this.total = parseFloat((this.lpprice * this.runDay).toFixed(2));
      } else if(formType === 'yyd'){
        this.total = parseFloat((form.dis * this.price * this.runDay).toFixed(2));
      }else if(formType === 'kp'){
        this.total = parseFloat((form.dis * this.kpprice * this.runDay).toFixed(2));
      }else if(formType === 'ym'){
        this.total = parseFloat((form.dis * this.ymprice * this.runDay).toFixed(2));
      }
    },

    // 将时间字符串（HH:mm）转换为分钟数
    timeToMinutes(time) {
      const [hours, minutes] = time.split(':');
      return parseInt(hours) * 60 + parseInt(minutes);
    },

    // 将分钟数转换为时间字符串（HH:mm）
    minutesToTime(minutes) {
      const hours = Math.floor(minutes / 60);
      const mins = minutes % 60;
      return `${String(hours).padStart(2, '0')}:${String(mins).padStart(2, '0')}`;
    },

    // 生成指定范围内的随机整数
    getRandomInt(min, max) {
      return Math.floor(Math.random() * (max - min + 1)) + min;
    },

    // 延迟任务
    async delayTask(index, row) {
      this.$confirm('确定将此任务移至最后吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          this.delayBtnLoading = true;
          console.log(row)
          row.yyd_order_id = this.yyd_order_id;
          try {
            // const requestData = {
            //   run_task_id: row.run_task_id,
            //   yyd_order_id: this.yyd_order_id,
            // };
            const requestData = {
              run_task_id: row.run_task_id,
            };
            
            if (this.type == 2) {
              requestData.bdlp_order_id = this.yyd_order_id; // 假设即使 type=2，值仍然来自 row.yyd_order_id
              console.log(requestData)
            } else if (this.type == 3) {
              requestData.keep_order_id = this.yyd_order_id; // 假设即使 type=2，值仍然来自 row.yyd_order_id
              console.log(requestData)
            } else if (this.type == 4) {
              requestData.ymty_order_id = this.yyd_order_id; // 假设即使 type=2，值仍然来自 row.yyd_order_id
              console.log(requestData)
            }else {
              requestData.yyd_order_id = this.yyd_order_id;
              console.log(requestData)
            }
            const { data } = await axios.post('/newjingyu/api01.php?act=delay&type=' + this.type, requestData);
            if (data.code === 0) {
              this.$message.success('修改成功');
              this.fetchTaskData(row);
            } else {
              this.$message.error(data.msg);
            }
          } catch (error) {
            this.$message.error('请求失败: ' + (error.response?.data?.msg || error.message));
          } finally {
            this.delayBtnLoading = false;
          }
        })
        .catch(() => {
          this.$message.info('已取消操作');
        });
    },

    // 申请退款
    async handleRefund(row) {
            await this.preventDuplicateClick('handleRefund', async () => {
      await this.$confirm('确定要删除订单吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(async () => {
          try {
            const requestData = {
              agg_order_id: row.yid,
            };
            const { data } = await axios.post('/newjingyu/api01.php?act=refund&type=' + row.type, requestData);
            if (data.code === 0) {
              this.$message.success('删除成功');
              this.get();
            } else {
              this.$message.error(data.msg);
            }
          } catch (error) {
            this.$message.error('请求失败: ' + (error.response?.data?.msg || error.message));
          }
        })
        .catch(() => {
          this.$message.info('已取消操作');
        });
      // 原有handleRefund方法内容...
    });
    },
  
    // 进入任务编辑模式
    handleTaskEdit(index, row) {
      this.$set(row, 'edit', true);
    },  
    
    async doneTaskEdit(index, row) {
      this.$set(row, 'edit', false);
      const requestData = {
        run_task_id: row.run_task_id,
        start_time: row.start_time,
      };
      const { data } = await axios.post('/newjingyu/api01.php?act=change&type=' + this.type, requestData);
      if (data.code === 0) {
        this.$message.success('修改成功');
        this.editDialogVisible = false;
        this.fetchTaskData(row);
      } else {
        this.$message.error(data.msg);
      }
    },
       
    // 取消任务编辑
    closeTaskEdit(index, row) {
      this.$set(row, 'edit', false);
      this.$message.info('已取消编辑');
    },
      
    // 打开任务弹窗
    async openTaskDialog(row) {
      this.taskDialogVisible = true;
      this.taskLoading = true;
      this.yyd_order_id = row.yyd_order_id;
      this.type = row.type;
      this.fetchTaskData(row);
     
    },
    
    async fetchTaskData(row) {
        let url = '/newjingyu/api01.php?act=getTask';
        // if (this.type == 2) {
        //     url = '/newjingyu/api01.php?act=get_lp_task';
        // } else if (this.type == 3) {
        //     url = '/newjingyu/api01.php?act=get_kp_task'; // 假设 KEEP 任务的后端接口
        // }
        
        // 调用后端接口获取用户信息
        const response = await axios.get(url, {
            params: {
                yid: row.yyd_order_id,
                type:this.type
            }
        });
    // 检查接口返回的数据
    if (response.data.code === 0) {
        console.log(response.data)
        this.taskData = response.data.data.list;
        this.taskLoading = false; // 显示加载状态
    }    
  },

   async getUserInfo() {
      await this.preventDuplicateClick('getUserInfo', async () => {
      // 原有getUserInfo方法内容...
      // 校验表单数据
  if (!this.addForm.school_id) {
    this.$message.error('请选择学校');
    return;
  }
  if (!this.addForm.number) {
    this.$message.error('请输入用户账号');
    return;
  }
  if (!this.addForm.password) {
    this.$message.error('请输入用户密码');
    return;
  }

  try {
    // 调用后端接口获取用户信息
    const response = await axios.get('/newjingyu/api01.php?act=get_user_info', {
      params: {
        school_id: this.addForm.school_id,
        number: this.addForm.number,
        password: this.addForm.password
      }
    });

    // 检查接口返回的数据
    if (response.data.code === 0) {
      const userInfo = response.data.data.student;
      this.$message.success('查询成功');

      // 填充用户信息到 addForm
      this.addForm.student_id = userInfo.student_id; // 设置学生ID
      this.addForm.school_name = userInfo.school.name; // 设置学校名称

      // 处理跑步规则
      this.zoneOptions = userInfo.run_rule_items.map(rule => ({
        zone_id: rule.run_rule_item_id,
        name: rule.zone.name
      }));

      // 默认选择第一个跑步区域
      if (this.zoneOptions.length > 0) {
        this.addForm.zone_id = this.zoneOptions[0].zone_id;
      }

      // 处理跑步规则的时间段
      this.runRules = userInfo.run_rule_items.map(rule => ({
        ...rule,
        time_slot: rule.time_slot.map(slot => ({
          ...slot,
          week: slot.week.join(', ') // 将周几数组转换为字符串
        }))
      }));
    
      // 提示用户信息已加载
      this.$message.success('用户信息已加载');
    } else {
      this.$message.error('查询失败: ' + response.data.msg);
    }
  } catch (error) {
    console.error('请求失败:', error);
    this.$message.error('请求失败，请稍后重试');
  }
    });
  
},
async getkpInfo() {
     await this.preventDuplicateClick('getkpInfo', async () => {
      // 原有getkpInfo方法内容...
      // 校验表单数据
  if (!this.addkpForm.phone) {
    this.$message.error('请输入用户账号（手机号）');
    return;
  }
  if (!this.addkpForm.password) {
    this.$message.error('请输入用户密码');
    return;
  }

  try {
    // 调用后端接口获取用户信息（假设接口相同，参数不同）
    const response = await axios.get('/newjingyu/api01.php?act=get_keep_info', {
      params: {
        phone: this.addkpForm.phone,  // 第一个接口用phone而不是number
        password: this.addkpForm.password
      }
    });

    // 检查接口返回的数据
    if (response.data.code === 0) {
      const userInfo = response.data.data.student;
      // 填充用户信息到 addkpForm
      this.addkpForm.student_id = userInfo.student_id; // 设置学生ID
      
      // 第一个接口没有school.name，但有default_zone.name
      this.addkpForm.school_name = userInfo.default_zone.name; // 设置学校名称（来自default_zone）

      // 处理跑步区域（第一个接口只有default_zone）
      this.zoneOptions = [{
        zone_id: userInfo.default_zone_id, // 使用default_zone_id
        name: userInfo.default_zone.name   // 使用default_zone.name
      }];
      
      this.addkpForm.student_id = userInfo.student_id;

      // 默认选择跑步区域（第一个接口只有一个区域）
      this.addkpForm.zone_id = this.zoneOptions[0].zone_id;
      
      this.addkpForm.dis = 2;
      this.addkpForm.min_minute = 3;
      this.addkpForm.max_minute = 8;

      // 第一个接口没有run_rule_items，所以不需要处理时间段
      this.runRules = []; // 设为空数组或根据需要填充默认值
     
      this.$message.success('用户信息已加载');
    } else {
      this.$message.error('查询失败: ' + response.data.msg);
    }
  } catch (error) {
    console.error('请求失败:', error);
    this.$message.error('请求失败，请稍后重试');
  }
    });
  
},
updateRunRuleByType(runType) {
    if (runType === '2') {
      // 自由跑使用默认值
      this.runTimeRange = ['06:00', '21:30'];
      this.addymForm.dis = 2;
    } else {
      // 查找对应的规则项
      const ruleItem = Object.values(this.runRules.items).find(
        item => item.run_type === runType
      );
      
      if (ruleItem && ruleItem.time_slot) {
        this.runTimeRange = [
          ruleItem.time_slot[0]?.beg || '06:00',
          ruleItem.time_slot[0]?.end || '21:30'
        ];
        this.addymForm.dis = ruleItem.min_dis || 2;
      }
    }
  },
  
  handleRunTypeChange(type) {
    this.updateRunRuleByType(type);
  },
async getYmInfo() {
     await this.preventDuplicateClick('getYmInfo', async () => {
      // 原有getkpInfo方法内容...
      // 校验表单数据
  if (!this.addymForm.phone) {
    this.$message.error('请输入用户账号（手机号）');
    return;
  }
  if (!this.addymForm.password) {
    this.$message.error('请输入用户密码');
    return;
  }

  try {
    // 调用后端接口获取用户信息（假设接口相同，参数不同）
    const response = await axios.get('/newjingyu/api01.php?act=get_keep_info', {
      params: {
        phone: this.addymForm.phone,  // 第一个接口用phone而不是number
        password: this.addymForm.password,
        type: 4
      }
    });

    // 检查接口返回的数据
    if (response.data.code === 0) {
      const userInfo = response.data.data.student;
      // 填充用户信息到 addymForm
      this.addymForm.student_id = userInfo.student_id; // 设置学生ID
      
      // 第一个接口没有school.name，但有default_zone.name
      this.addymForm.school_name = userInfo.school.name; // 设置学校名称（来自default_zone）

      this.zoneOptions = response.data.data.zone_list;
      
      // 默认选择跑步区域（第一个接口只有一个区域）
      this.addymForm.zone_id = userInfo.default_zone_id;
      
     
      // 在获取用户信息后的处理逻辑中
        if (userInfo.run_rule != null && userInfo.run_rule.items) {
          this.runRules = userInfo.run_rule;
          
          // 提取支持的跑步类型
          const supportedTypes = Object.keys(userInfo.run_rule.items).map(key => 
            userInfo.run_rule.items[key].run_type
          );
          
          // 设置支持的跑步类型（自由跑2总是支持）
          this.supportedRunTypes = [...new Set([...supportedTypes, '2'])];
          
          // 初始化跑步规则选项
          this.runTypeOptions = [
            { label: '晨跑', value: '4', disabled: !supportedTypes.includes('4') },
            { label: '长跑', value: '5', disabled: !supportedTypes.includes('5') },
            { label: '重修', value: '6', disabled: !supportedTypes.includes('6') },
            { label: '自由跑', value: '2', disabled: false }
          ];
          
          // 设置默认选中的跑步类型（第一个支持的规则或自由跑）
          const defaultType = supportedTypes.length > 0 ? supportedTypes[0] : '2';
          this.addymForm.run_type = defaultType;
          
          // 初始化跑步时间和距离
          this.updateRunRuleByType(defaultType);
        } else {
          // 默认只有自由跑可用
          this.runTypeOptions = [
            { label: '晨跑', value: '4', disabled: true },
            { label: '长跑', value: '5', disabled: true },
            { label: '重修', value: '6', disabled: true },
            { label: '自由跑', value: '2', disabled: false }
          ];
          this.addymForm.run_type = '2';
          this.runTimeRange = ['06:00', '21:30'];
          this.addymForm.dis = 2;
        }

      
      this.$message.success('用户信息已加载');
    } else {
      this.$message.error('查询失败: ' + response.data.msg);
    }
  } catch (error) {
    console.error('请求失败:', error);
    this.$message.error('请求失败，请稍后重试');
  }
    });
  
},
async getlpInfo() {
    await this.preventDuplicateClick('getlpInfo', async () => {
      // 原有getlpInfo方法内容...
      // 校验表单数据
  if (!this.addlpForm.uid) {
    this.$message.error('请输入乐跑id');
    return;
  }
  try {
    // 调用后端接口获取用户信息
    const response = await axios.get('/newjingyu/api01.php?act=get_lp_info', {
      params: {
        uid: this.addlpForm.uid,
      }
    });

    // 检查接口返回的数据
    if (response.data.code === 0) {
      const userInfo = response.data.data.student;
      this.$message.success('查询成功');
      
      // 设置默认跑步时间段（取第一个时间段）
      if (userInfo.run_rule != null) {
        const firstTimeSlot = userInfo.run_rule.time_slot[0];
        this.runTimeRange = [firstTimeSlot.beg, firstTimeSlot.end];
        this.addlpForm.dis = userInfo.run_rule.min_dis || 1.5;
      }else{
          this.runTimeRange = ['08:00', '22:00'];
          this.addlpForm.dis =  1.5;
      }

      // 调用后端接口获取区域数据
      const response01 = await axios.get('/newjingyu/api01.php?act=get_zone_data', {
        params: {
          uid: this.addlpForm.uid,
        }
      });

      if (response01.data.code === 0) {
        this.zonelpOptions = response01.data.data.list
          .filter(rule => rule.can_run)
          .map(rule => ({
            zone_id: rule.zone_id,
            name: rule.name,
            school_name: rule.school.name
          }));

        if (this.zonelpOptions.length > 0) {
          const defaultZone = this.zonelpOptions.find(
            zone => zone.zone_id === userInfo.default_zone_id
          );
          this.addlpForm.zone_id = defaultZone 
            ? defaultZone.zone_id 
            : this.zonelpOptions[0].zone_id;
          this.addlpForm.school_name = defaultZone 
            ? defaultZone.name
            : this.zonelpOptions[0].name;        
        }
      }
      
      // 填充其他用户信息
      this.addForm.student_id = userInfo.uid;
      this.addForm.school_name = userInfo.school.name;
     
      // 处理跑步规则选项
      this.zoneOptions = userInfo.run_rule.time_slot.map((slot, index) => ({
        zone_id: `time_slot_${index}`,
        name: `${slot.name} (${slot.beg}-${slot.end})`
      }));

      if (this.zoneOptions.length > 0) {
        this.addForm.zone_id = this.zoneOptions[0].zone_id;
      }

      // 处理跑步规则的时间段
      this.runRules = [{
        ...userInfo.run_rule,
        time_slot: userInfo.run_rule.time_slot.map(slot => ({
          ...slot,
          week: slot.week ? slot.week.join(', ') : '无'
        }))
      }];
    
      this.$message.success('用户信息已加载');
    } else {
      this.$message.error('查询失败: ' + response.data.msg);
    }
  } catch (error) {
    console.error('请求失败:', error);
    this.$message.error('请求失败，请稍后重试');
  }
    });
  
},
    // 提交订单
    async handleAdd() {
        
        await this.preventDuplicateClick('handleAdd', async () => {
            // 校验表单数据
      if (!this.addForm.school_id) {
        this.$message.error('请选择学校');
        return;
      }
      if (!this.addForm.number) {
        this.$message.error('请输入用户账号');
        return;
      }
      if (!this.addForm.dis) {
        this.$message.error('请输入公里数');
        return;
      }
      if (!this.addForm.task_list || this.addForm.task_list.length === 0) {
        this.$message.error('请生成跑步任务');
        return;
      }

      // 构造请求数据
      const requestData = {
        task_list: this.addForm.task_list.map(task => ({
          start_time: task.start_time
        })),
        school_id: this.addForm.school_id,
        number: this.addForm.number,
        dis: this.addForm.dis,
        run_rule_item_id: this.addForm.zone_id, // 需要从跑步规则中获取
        run_type: 'valid', // 固定值
        student_id: this.addForm.student_id,
        school_name: this.addForm.school_name,
        user: this.addForm.number,
        pass: this.addForm.password,
        num: this.runDay,
        repair: false // 固定值
      };

      try {
        // 调用后端接口提交数据
        const response = await axios.post('/newjingyu/api01.php?act=add', requestData);

        // 检查接口返回的数据
        if (response.data.code === 0) {
          this.$message.success('下单成功');
          this.addDialogVisible = false; // 关闭弹窗
          this.resetForm(); // 重置表单
          this.get();
        } else {
          this.$message.error('下单失败: ' + response.data.msg);
        }
      } catch (error) {
        console.error('请求失败:', error);
        this.$message.error('请求失败，请稍后重试');
      }
    });
     
    },

    // 重置表单
    resetForm() {
      this.addForm = {
        school_id: '',
        number: '',
        password: '',
        student_id: '',
        school_name: '',
        zone_id: '',
        dis: 2,
        task_list: [],
        run_rule_item_id: ''
      };
      this.total = 0;
      this.runStartDate = '';
      this.runTimeRange = '';
      this.runWeek = [1, 2, 3, 4, 5, 6, 0],
      this.runDay = 1;
    },
  // 提交订单方法
async handlekpAdd() {
    await this.preventDuplicateClick('handlekpAdd', async () => {
      // 原有handlekpAdd方法内容...
      // 表单校验
  if (!this.addkpForm.phone) {
    this.$message.error('请输入用户账号');
    return;
  }
  if (!this.addkpForm.password) {
    this.$message.error('请输入用户密码');
    return;
  }
  if (!this.addkpForm.student_id) {
    this.$message.error('请先查询用户信息');
    return;
  }
  if (!this.addkpForm.zone_id) {
    this.$message.error('请选择跑步区域');
    return;
  }
  if (!this.addkpForm.task_list || this.addkpForm.task_list.length === 0) {
    this.$message.error('请分配跑步时间');
    return;
  }

  // 固定参数配置
  const fixedParams = {
    // 固定跑步类型（根据表单选择）
    run_type: this.addkpForm.run_type || '1', // 默认为自由跑
    
    // 固定customs配置
    customs: {
      min_duration: 0,
      max_duration: 0,
      min_frequency: 100,
      max_frequency: 200,
      km_calorie: 0,
      climb_height: 0,
      is_fix_start: false
    },
    
    // 精确距离设为false
    is_accuracy_dis: false,
    
    // 其他固定参数
    min_minute: this.addymForm.min_minute || 3, // 默认3分钟/公里
    max_minute: this.addymForm.max_minute || 8  // 默认8分钟/公里
  };

  // 构造请求数据
  const requestData = {
    // 表单填写的参数
    phone: this.addkpForm.phone,
    password: this.addkpForm.password,
    student_id: this.addkpForm.student_id,
    school_name: this.addkpForm.school_name,
    dis: this.addkpForm.dis,
    zone_id: this.addkpForm.zone_id,
    task_list: this.addkpForm.task_list.map(task => ({
      start_time: task.start_time
    })),
    
    // 合并固定参数
    ...fixedParams
  };

  try {
    // 调用下单接口
    const response = await axios.post('/newjingyu/api01.php?act=kpadd', requestData);
    
    if (response.data.code === 0) {
      this.$message.success('下单成功');
      this.addkpDialogVisible = false;
      this.resetForm();
      this.get();
    } else {
      this.$message.error(response.data.msg || '下单失败');
    }
  } catch (error) {
    console.error('下单请求失败:', error);
    this.$message.error('网络错误，请稍后重试');
  }
    });
  
},
   // 提交订单方法
async handleymAdd() {
    await this.preventDuplicateClick('handleymAdd', async () => {
      // 原有handlekpAdd方法内容...
      // 表单校验
  if (!this.addymForm.phone) {
    this.$message.error('请输入用户账号');
    return;
  }
  if (!this.addymForm.password) {
    this.$message.error('请输入用户密码');
    return;
  }
  if (!this.addymForm.student_id) {
    this.$message.error('请先查询用户信息');
    return;
  }
  if (!this.addymForm.zone_id) {
    this.$message.error('请选择跑步区域');
    return;
  }
    if (!this.addymForm.run_type) {
    this.$message.error('请选择跑步类型');
    return;
  }
  if (!this.addymForm.task_list || this.addymForm.task_list.length === 0) {
    this.$message.error('请分配跑步时间');
    return;
  }
  // 构造请求数据
  const requestData = {
    // 表单填写的参数
    phone: this.addymForm.phone,
    password: this.addymForm.password,
    student_id: this.addymForm.student_id,
    school_name: this.addymForm.school_name,
    dis: this.addymForm.dis,
    zone_id: this.addymForm.zone_id,
    task_list: this.addymForm.task_list.map(task => ({
      start_time: task.start_time
    })),
    repair:this.addymForm.repair,
    run_type:this.addymForm.run_type
  };

  try {
    // 调用下单接口
    const response = await axios.post('/newjingyu/api01.php?act=ymadd', requestData);
    
    if (response.data.code === 0) {
      this.$message.success('下单成功');
      this.addymDialogVisible = false;
      this.resetForm();
      this.fetchOrderList(); // 刷新订单列表
    } else {
      this.$message.error(response.data.msg || '下单失败');
    }
  } catch (error) {
    console.error('下单请求失败:', error);
    // this.$message.error('网络错误，请稍后重试');
  }
    });
  
},
      // 提交订单
    async handlelpAdd() {
         await this.preventDuplicateClick('handlelpAdd', async () => {
             if (!this.addlpForm.uid) {
        this.$message.error('请输入乐跑ID');
        return;
      }
      if (!this.addlpForm.dis) {
        this.$message.error('请输入公里数');
        return;
      }
      if (!this.addlpForm.task_list || this.addlpForm.task_list.length === 0) {
        this.$message.error('请生成跑步任务');
        return;
      }
      

      // 构造请求数据
      const requestData = {
        task_list: this.addlpForm.task_list.map(task => ({
          start_time: task.start_time
        })),
        upload_type: 'SLOW',
        uid: this.addlpForm.uid,
        is_jrxy:false,
        school_name: this.addlpForm.school_name,
        dis: this.addlpForm.dis,
        zone_id: this.addlpForm.zone_id, // 需要从跑步规则中获取
        run_type: this.addlpForm.run_type, // 固定值
          customs: {
            min_sec: 0,  // 最小时间限制（秒）
            max_sec: 0   // 最大时间限制（秒）
          }
      };

      try {
        // 调用后端接口提交数据
        const response = await axios.post('/newjingyu/api01.php?act=lpadd', requestData);

        // 检查接口返回的数据
        if (response.data.code === 0) {
          this.$message.success('下单成功');
          this.addDialogVisible = false; // 关闭弹窗
          this.resetForm(); // 重置表单
          this.get();
        } else {
          this.$message.error('下单失败: ' + response.data.msg);
        }
      } catch (error) {
        console.error('请求失败:', error);
        this.$message.error('请求失败，请稍后重试');
      }
    });
    },

    // 重置表单
    resetForm() {
      this.addForm = {
        school_id: '',
        number: '',
        password: '',
        student_id: '',
        school_name: '',
        zone_id: '',
        dis: 2,
        task_list: [],
        run_rule_item_id: ''
      };
      this.total = 0;
      this.runStartDate = '';
      this.runTimeRange = '';
      this.runWeek = [1, 2, 3, 4, 5, 6, 0],
      this.runDay = 0;
    },
    async handleEdit() {
      const { data } = await axios.post('/jingyu/api.php?appId=bdlp&act=bdlp_edit', {
        form: this.editForm
      });
      if (data.code === 1) {
        this.$message.success('修改成功');
        this.editDialogVisible = false;
        this.get();
      } else {
        this.$message.error(data.msg);
      }
    },
    async get() {
      this.tableLoading = true;
      const { data } = await axios.post('/newjingyu/api01.php?appId=yyd&act=orders', {
        page: this.pagination.page,
        limit: this.pagination.limit,
        type: this.search.type,
        keywords: this.search.keywords
      });
      this.tableLoading = false;
      if (data.code === 1) {
        this.tableData = data.data;
        this.pagination.total = data.pagination.total;
      } else {
        this.$message.error(data.msg);
      }
    },
      async getPrice() {
      const { data } = await axios.post('/newjingyu/api01.php?act=get_price', {
        keywords: this.search.keywords
      });
      if (data.code === 1) {
        this.price = data.data;
        this.lpprice = data.lpdata;
        this.kpprice = data.kpdata;
        this.ymprice = data.ymdata;
      } else {
        this.$message.error(data.msg);
      }
    },
   addHandleClose() {
    this.addDialogVisible = false;
     this.addlpDialogVisible = false;
     this.addkpDialogVisible = false;
     this.addymDialogVisible = false;
    },
  genRunDateAndTime() {
    // 清空之前的任务列表
    this.addForm.task_list = [];

    // 如果没有选择开始日期或跑步天数，直接返回
    if (!this.runStartDate || !this.runDay) {
      this.$message.warning('请选择开始日期和跑步天数');
      return;
    }

    // 如果没有选择跑步时段，直接返回
    if (!this.runTimeRange || this.runTimeRange.length !== 2) {
      this.$message.warning('请选择跑步时段');
      return;
    }

    // 如果没有选择跑步周期，直接返回
    if (!this.runWeek || this.runWeek.length === 0) {
      this.$message.warning('请选择跑步周期');
      return;
    }

    // 解析跑步时段
    const [startTime, endTime] = this.runTimeRange;

    // 将开始日期转换为 Date 对象
    const startDate = new Date(this.runStartDate);

    // 将跑步时段转换为分钟数
    const startMinutes = this.timeToMinutes(startTime);
    const endMinutes = this.timeToMinutes(endTime);

    // 生成任务列表
    for (let i = 0; i < this.runDay; i++) {
      // 计算当前日期
      const currentDate = new Date(startDate);
      currentDate.setDate(startDate.getDate() + i);

      // 获取当前日期的星期几（0-6，0 表示周日）
      const dayOfWeek = currentDate.getDay();

      // 检查当前日期是否符合跑步周期
      if (this.runWeek.includes(dayOfWeek)) {
        // 随机生成一个时间点（在跑步时段内）
        const randomMinutes = this.getRandomInt(startMinutes, endMinutes - 30); // 假设跑步时长为 30 分钟
        const randomTime = this.minutesToTime(randomMinutes);

        // 生成任务时间（格式：YYYY-MM-DD HH:mm:ss）
        const startDateTime = `${currentDate.toISOString().split('T')[0]} ${randomTime}:00`;
        const endDateTime = `${currentDate.toISOString().split('T')[0]} ${this.minutesToTime(randomMinutes + 30)}:00`; // 假设跑步时长为 30 分钟

        // 将任务添加到任务列表
        this.addForm.task_list.push({
          start_time: startDateTime,
          end_time: endDateTime
        });
      }
    }

    // 计算价格总计
    this.total = parseFloat((this.addForm.dis * this.price * this.runDay).toFixed(2));
  },
  genlpRunDateAndTime() {
    // 清空之前的任务列表
    this.addlpForm.task_list = [];

    // 如果没有选择开始日期或跑步天数，直接返回
    if (!this.runStartDate || !this.runDay) {
      this.$message.warning('请选择开始日期和跑步天数');
      return;
    }

    // 如果没有选择跑步时段，直接返回
    if (!this.runTimeRange || this.runTimeRange.length !== 2) {
      this.$message.warning('请选择跑步时段');
      return;
    }

    // 如果没有选择跑步周期，直接返回
    if (!this.runWeek || this.runWeek.length === 0) {
      this.$message.warning('请选择跑步周期');
      return;
    }

    // 解析跑步时段
    const [startTime, endTime] = this.runTimeRange;

    // 将开始日期转换为 Date 对象
    const startDate = new Date(this.runStartDate);

    // 将跑步时段转换为分钟数
    const startMinutes = this.timeToMinutes(startTime);
    const endMinutes = this.timeToMinutes(endTime);

    // 生成任务列表
    for (let i = 0; i < this.runDay; i++) {
      // 计算当前日期
      const currentDate = new Date(startDate);
      currentDate.setDate(startDate.getDate() + i);

      // 获取当前日期的星期几（0-6，0 表示周日）
      const dayOfWeek = currentDate.getDay();

      // 检查当前日期是否符合跑步周期
      if (this.runWeek.includes(dayOfWeek)) {
        // 随机生成一个时间点（在跑步时段内）
        const randomMinutes = this.getRandomInt(startMinutes, endMinutes - 30); // 假设跑步时长为 30 分钟
        const randomTime = this.minutesToTime(randomMinutes);

        // 生成任务时间（格式：YYYY-MM-DD HH:mm:ss）
        const startDateTime = `${currentDate.toISOString().split('T')[0]} ${randomTime}:00`;
        const endDateTime = `${currentDate.toISOString().split('T')[0]} ${this.minutesToTime(randomMinutes + 30)}:00`; // 假设跑步时长为 30 分钟

        // 将任务添加到任务列表
        this.addlpForm.task_list.push({
          start_time: startDateTime,
          end_time: endDateTime
        });
      }
    }

    // 计算价格总计
    this.total = parseFloat((this.addlpForm.dis * this.price * this.runDay).toFixed(2));
  },

  // 将时间字符串（HH:mm）转换为分钟数
  timeToMinutes(time) {
    const [hours, minutes] = time.split(':');
    return parseInt(hours) * 60 + parseInt(minutes);
  },

  // 将分钟数转换为时间字符串（HH:mm）
  minutesToTime(minutes) {
    const hours = Math.floor(minutes / 60);
    const mins = minutes % 60;
    return `${String(hours).padStart(2, '0')}:${String(mins).padStart(2, '0')}`;
  },

  // 生成指定范围内的随机整数
  getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
  },
    editHandleClose(){
        
    },
    taskHandleClose(){
        this.taskDialogVisible = false;
    },
    handleSizeChange(val) {
      this.pagination.limit = val;
      this.get();
    },
    handleCurrentChange(val) {
      this.pagination.page = val;
      this.get();
    },
    async remoteMethod(query) {
      // 如果输入内容为空，清空选项
      if (!query) {
        this.schoolOptions = [];
        return;
      }

      // 设置加载状态为 true
      this.schoolLoading = true;

      try {
        // 调用后端接口，传递用户输入的内容
        const response = await axios.get('/newjingyu/api01.php?act=get_school_data', {
          params: {
            school: query, // 将用户输入的内容作为参数传递给接口
          },
        });

        // 检查接口返回的数据
        if (response.data.code === 0) {
          // 将接口返回的学校列表赋值给 schoolOptions
          this.schoolOptions = response.data.data.list;
        } else {
          // 如果接口返回错误，清空选项
          this.schoolOptions = [];
          console.error('接口返回错误:', response.data.msg);
        }
      } catch (error) {
        // 处理请求错误
        console.error('请求失败:', error);
        this.schoolOptions = [];
      } finally {
        // 设置加载状态为 false
        this.schoolLoading = false;
      }
    }
  },
  mounted() {
    this.get();
    this.getPrice();
    this.showAnnouncement();
  }
});
</script>
</body>